/*!
 
 @Name: layer v1.9.x-ext
 @Author: 贤心
 @Api：http://sentsin.com/jquery/layer

 */
 
;!function(){
 
layer.use('skin/layer.ext.css', function(){
    layer.layui_layer_extendlayerextjs = true;
});

var cache = layer.cache||{}, skin = function(type){
    return (cache.skin ? (' ' + cache.skin + ' ' + cache.skin + '-'+type) : '');
}

//仿系统prompt
layer.prompt = function(options, yes){
    options = options || {};
    if(typeof options === 'function') yes = options;
    var prompt, content = options.formType == 2 ? '<textarea class="layui-layer-input">'+ (options.value||'') +'</textarea>' : function(){
        return '<input type="'+ (options.formType == 1 ? 'password' : 'text') +'" class="layui-layer-input" value="'+ (options.value||'') +'">';
    }();
    return layer.open($.extend({
        btn: ['&#x786E;&#x5B9A;','&#x53D6;&#x6D88;'],
        content: content,
        skin: 'layui-layer-prompt' + skin('prompt'),
        success: function(layero){
            prompt = layero.find('.layui-layer-input');
            prompt.focus();
        }, yes: function(index){
            var value = prompt.val();
            if(value === ''){
                prompt.focus();
            } else if(value.length > (options.maxlength||500)) {
                layer.tips('&#x6700;&#x591A;&#x8F93;&#x5165;'+ (options.maxlength || 500) +'&#x4E2A;&#x5B57;&#x6570;', prompt, {tips: 1});
            } else {
                yes && yes(value, index, prompt);
            }
        }
    }, options));
};

//tab层
layer.tab = function(options){
    options = options || {};
    var tab = options.tab || {};
    return layer.open($.extend({
        type: 1,
        skin: 'layui-layer-tab' + skin('tab'),
        title: function(){
            var len = tab.length, ii = 1, str = '';
            if(len > 0){
                str = '<span class="layui-layer-tabnow">'+ tab[0].title +'</span>';
                for(; ii < len; ii++){
                    str += '<span>'+ tab[ii].title +'</span>';
                }
            }
            return str;
        }(),
        content: '<ul class="layui-layer-tabmain">'+ function(){
            var len = tab.length, ii = 1, str = '';
            if(len > 0){
                str = '<li class="layui-layer-tabli xubox_tab_layer">'+ (tab[0].content || 'no content') +'</li>';
                for(; ii < len; ii++){
                    str += '<li class="layui-layer-tabli">'+ (tab[ii].content || 'no  content') +'</li>';
                }
            }
            return str;
        }() +'</ul>',
        success: function(layero){
            var btn = layero.find('.layui-layer-title').children();
            var main = layero.find('.layui-layer-tabmain').children();
            btn.on('mousedown', function(e){
                e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
                var othis = $(this), index = othis.index();
                othis.addClass('layui-layer-tabnow').siblings().removeClass('layui-layer-tabnow');
                main.eq(index).show().siblings().hide();
            });
        }
    }, options));
};

//相册层
layer.photos = function(options, loop, key){
    var dict = {};
    options = options || {};
    if(!options.photos) return;
    var type = options.photos.constructor === Object;
    var photos = type ? options.photos : {}, data = photos.data || [];
    var start = photos.start || 0;
    dict.imgIndex = start + 1;

    if(!type){ //页面直接获取
        var parent = $(options.photos), img = parent.find(options.img||'img');
        if (img.length === 0) return;
        loop || parent.find(photos.img||'img').each(function(index){
            var othis = $(this);
            data.push({
                alt: othis.attr('alt'),
                pid: othis.attr('layer-pid'),
                src: othis.attr('layer-src') || othis.attr('src'),
                thumb: othis.attr('src')
            });
            othis.on('click', function(){
                layer.photos($.extend(options, {
                    photos: {
                        start: index,
                        data: data,
                        tab: options.tab
                    },
                    full: options.full
                }), true);
            });
        });
        
        //不直接弹出
        if(!loop) return;
        
    } else if (data.length === 0){
        layer.msg('&#x6CA1;&#x6709;&#x56FE;&#x7247;');
        return;
    }
    
    //上一张
    dict.imgprev = function(key){
        dict.imgIndex--;
        if(dict.imgIndex < 1){
            dict.imgIndex = data.length;
        }
        dict.tabimg(key);
    };
    
    //下一张
    dict.imgnext = function(key,errorMsg){
        dict.imgIndex++;
        if(dict.imgIndex > data.length){
            dict.imgIndex = 1;
            if (errorMsg) {return};
        }
        dict.tabimg(key)
    };

    // 旋转
    dict.imgdeg = function(dom){
        var width = dict['naturalWidth'];
        var height = dict['naturalHeight'];
        var maxWidth = dict['maxWidth'];
        var maxHeight = dict['maxHeight'];
        var resize = 1;

        var img = $(dict.bigimg[0]).find('img:eq(0)');
        var src = img[0].src;
        var show = img.attr('data-show') || src;
        var source = img.attr('data-source') || show;

        if (width > maxWidth) {
            resize = maxWidth / width;
            height =  resize * height;
            width = maxWidth;
        };
        if (height > maxHeight) {
            resize = resize * maxHeight / height;
            width = maxHeight / height * width;
            height = maxHeight;
        };

        var target = dom,
            $this = $(dom),
            go = target.getAttribute('data-go'),
            degree = parseInt($this.attr('artZoom-degree')) || 0;
            

        
        switch (go) {
            case 'left':
                degree -= 90;
                degree = degree === -90 ? 270 : degree;
                break;
            case 'right':
                degree += 90;
                degree = degree === 360 ? 0 : degree;
                break;
            case 'source':
            	var _url = source || show || src;
            	var source_url = _url.replace(/upload\//gi,'original/');
                window.open(source_url);
                break;
        };

        if ((go === 'left' || go === 'right')) {
            imgRotate(dict,degree,options);
            $('[data-go]').attr('artZoom-degree', degree);
        }

    };
    
    //方向键
    dict.keyup = function(event){
        if(!dict.end){
            var code = event.keyCode;
            event.preventDefault();
            if(code === 37){
                dict.imgprev(true);
            } else if(code === 39) {
                dict.imgnext(true);
            } else if(code === 27) {
                layer.close(dict.index);
            }
        }
    }
    
    //切换
    dict.tabimg = function(key){
        if(data.length <= 1) return;
        photos.start = dict.imgIndex - 1;
        layer.close(dict.index);
        layer.photos(options, true, key);
    }
    
    //一些动作
    dict.event = function(){
        dict.bigimg.hover(function(){
            dict.imgsee.show();
        }, function(){
            dict.imgsee.hide();
        });
        
        dict.bigimg.find('.layui-layer-imgprev').on('click', function(event){
            event.preventDefault();
            dict.imgprev();
        });  
        
        dict.bigimg.find('.layui-layer-imgnext').on('click', function(event){         
            event.preventDefault();
            dict.imgnext();
        });

        dict.bigimg.find('[data-go]').on('click', function(event){         
            event.preventDefault();
            dict.imgdeg(this);
        });
        
        dict.bigimg.find('.close').on('click', function(event){         
            layer.close(dict.index);
        });
        
        


        
        $(document).on('keyup', dict.keyup);
    };
    
    //图片预加载
    function loadImage(url, callback, error) {     
        var img = new Image();    
        img.onload = function(){
            img.onload = null;
            callback(img);
        };
        img.onerror = function(e){
            img.onerror = null;
            error(e);
        };
        img.src = url; 
    };
    
    dict.loadi = layer.load(1, {
        shade: 'shade' in options ? false : 0.9,
        scrollbar: false
    });
    loadImage(data[start].src, function(img){
        layer.close(dict.loadi);
        dict.index = layer.open($.extend({
            type: 1,
            area: function(){
               var imgarea = [img.width, img.height];
               var winarea = [$(window).width() - 100, $(window).height() - 100];


               
               var width = imgarea[0];
               var height = imgarea[1];
               var maxWidth = winarea[0];
               var maxHeight = winarea[1];
               var resize = 1;
 
               dict['naturalWidth'] = width;
               dict['naturalHeight'] = height;
               dict['maxWidth'] = maxWidth;
               dict['maxHeight'] = maxHeight;

                if (width > maxWidth) {
                    resize = maxWidth / width;
                    height =  resize * height;
                    width = maxWidth;
                };
                if (height > maxHeight) {
                    resize = resize * maxHeight / height;
                    width = maxHeight / height * width;
                    height = maxHeight;
                };



               // if(!options.full && imgarea[0] > winarea[0]){
               //     imgarea[0] = winarea[0];
               //     imgarea[1] = imgarea[0]*winarea[1]/imgarea[0];
               // }
               //hejianyi 修改超出浏览器大图bug
                // if (options.photos.maxImageWidth && imgarea[0]>options.photos.maxImageWidth) {
                //     imgarea[1] = imgarea[1]*(options.photos.maxImageWidth/imgarea[0]);
                //     imgarea[0] = options.photos.maxImageWidth;
                // } else {
                //     if(!options.full && imgarea[0] > winarea[0]){
                //        imgarea[1] = imgarea[1]*(winarea[0]/imgarea[0]);
                //        imgarea[0] = winarea[0];
                //     }
                // }
                width = parseInt(width) + 40;
                height = parseInt(height) + 40;
               return [width+'px', height+'px']; 
            }(),
            title: false,
            shade: 0.9,
            shadeClose: true,
            closeBtn: false,
            move: '.layui-layer-phimg img',
            moveType: 1,
            scrollbar: false,
            moveOut: true,
            shift: 7,
            skin: 'layui-layer-photos' + skin('photos'),
            content: '<div class="layui-layer-phimg">'
                +'<img src="'+ data[start].src +'" alt="'+ (data[start].alt||'') +'" layer-pid="'+ data[start].pid +'">'
                +'<span class="close"></span>'
                +'<div class="layui-layer-imgsee">'
                    +(data.length > 1 ? '<span class="layui-layer-imguide"><a href="javascript:;" class="layui-layer-iconext layui-layer-imgprev"></a><a href="javascript:;" class="layui-layer-iconext layui-layer-imgnext"></a></span>' : '')
                    +'<div class="layui-layer-imgbar" style="display:'+ (key ? 'block' : '') +'"><span class="layui-layer-imgtit"><a href="javascript:;">'+ (data[start].alt||'') +'</a><em>'+ dict.imgIndex +'/'+ data.length +'</em></span></div>'
               
                    +'<div class="view-oper">'
                        +'<a data-go="left">左旋转</a>'
                        +'<a data-go="right">右旋转</a>'
                        +'<a data-go="source">看原图</a>'
                    +'</div>'
                 +'</div>'
            +'</div>',
            success: function(layero, index){
                dict.bigimg = layero.find('.layui-layer-phimg');
                dict.imgsee = layero.find('.layui-layer-imguide,.layui-layer-imgbar,.view-oper');
                dict.event(layero);
                options.tab && options.tab(data[start], layero);
            }, end: function(){
                dict.end = true;
                $(document).off('keyup', dict.keyup);
            }
        }, options));
    }, function(){
        layer.close(dict.loadi);
        layer.msg('&#x5F53;&#x524D;&#x56FE;&#x7247;&#x5730;&#x5740;&#x5F02;&#x5E38;', {time: 2000}, function(){
            data.length > 1 && dict.imgnext(true,true);
        });
    });
};

}();



/**
 * 图片旋转
 * @version 2011.05.27
 * @author  TangBin
 * @param   {HTMLElement}   图片元素
 * @param   {Number}        旋转角度 (可用值: 0, 90, 180, 270)
 * @param   {Number}        最大宽度限制
 * @param   {Number}        最大高度限制
 */
var imgRotate = function (dict,degree,opts) {
    var layerImg = dict.bigimg.find('img')[0];
    var $layerImg = $(layerImg);
    var layerDiv = $layerImg.parents('.layui-layer-photos');
    var layerCont = $layerImg.parents('.layui-layer-content');

    $layerImg.hide();
    $('#artCanvas').remove();

    var x, y,
    isCanvas = !!document.createElement('canvas').getContext;

    var canvas = document.createElement(isCanvas ? 'canvas' : 'span');
    
    canvas.id = "artCanvas";
    layerImg.parentNode.insertBefore(canvas, layerImg.nextSibling);
    canvas.className = layerImg.className;
    canvas.title = layerImg.title;
    if (!isCanvas) {
        canvas.img = document.createElement('img');

        canvas.img.src = layerImg.src;
        canvas.appendChild(canvas.img);
        canvas.style.cssText = 'display:inline-block;*zoom:1;*display:inline;' +
            // css reset
            'padding:0;margin:0;border:none 0;position:static;float:none;overflow:hidden;width:auto;height:auto';
    };



    var width = dict['naturalWidth'];
    var height = dict['naturalHeight'];
    var maxWidth = dict['maxWidth'];
    var maxHeight = dict['maxHeight'];
    var resize = 1;

    var size = function (isSwap) {
        if (isSwap) width = [height, height = width][0];
        if (width > maxWidth) {
            resize = maxWidth / width;
            height =  resize * height;
            width = maxWidth;
        };
        if (height > maxHeight) {
            resize = resize * maxHeight / height;
            width = maxHeight / height * width;
            height = maxHeight;
        };
        if (isCanvas) (isSwap ? height : width) / dict.naturalWidth;
    };
    
    switch (degree) {
        case 0:
            x = 0;
            y = 0;
            size();
            break;
        case 90:
            x = 0;
            y = -dict.naturalHeight;
            size(true);
            break;
        case 180:
            x = -dict.naturalWidth;
            y = -dict.naturalHeight
            size();
            break;
        case 270:
            x = -dict.naturalWidth;
            y = 0;
            size(true);
            break;
    };

    if (isCanvas) {
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);
        getContext = canvas.getContext('2d');
        getContext.rotate(degree * Math.PI / 180);
        getContext.scale(resize, resize);
        getContext.drawImage(layerImg, x, y);   
    } else {
        
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';// 解决IE8使用滤镜后高度不能自适应
        canvas.img.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + degree / 90 + ')';

        if(degree / 90%2) {
            $(canvas.img).width(height);
            $(canvas.img).height(width);
        } else {
            $(canvas.img).width(width);
            $(canvas.img).height(height);
        }
    };


    var layerWidth = parseInt(width)+40;
    var layerHeight = parseInt(height)+40;
    var winWidth = $(window).width();
    var winHeight = $(window).height();
   
    var top = (winHeight-layerHeight)/2;
    var left = (winWidth- layerWidth)/2;
    
    if(typeof opts.offset === 'object') {
        top = typeof opts.offset[0];
    }

    layerCont.css({height:'auto'});
    layerDiv.css({width:layerWidth, height: layerHeight,left:left,top:top})
};

/*
 * img_car 车辆 ，pd_top
*/
$(document).on('mouseover','.td_position img,.nowrap img, .img_per, .img_car ',function(){
    $(this).css('cursor','pointer');
})

// 给单个图片添加
$(document).on('click','.td_position img, .nowrap img , .img_per  , .img_car  ',function(){
	
    if (this.nodeName !== 'IMG' || this.getAttribute('data-live') === 'stop') return false;
	var src = this.src;
	var v = src.lastIndexOf('no_imgage.png');
	if(v!=-1){
		return false;
	}
	v = src.lastIndexOf('bg_noimg.jpg'); 
	if(v!=-1){
		return false;
	}
	
    var photosData =[];
    var _data = {};
    _data.alt = $(this).attr('alt');
    _data.pid = $(this).attr('pid');
    _data.src = $(this).attr('src');
    _data.thumb = $(this).attr('thumb');
    photosData.push(_data);
    //弹窗基本参数
    var layerObj = {
    "title": "查看大图", //相册标题
    "id": new Date().getTime(), //相册id
    "start": 0,
    "shift": 6,
    "data": photosData
    ,'maxImageWidth':600
    };
    
    var dataObj = { photos: layerObj, move: false};
    
/*    var topPx = $(this).offset().top;
	var pageH = $(document).height();
	if(topPx+600>pageH) {
		topPx = pageH-600;
	} else if(topPx>300) {
		topPx = topPx-100;
	}
	dataObj.offset = [topPx+'px',''];*/
	
	var winH = document.body.offsetHeight ? document.body.offsetHeight : document.body.clientHeight;
	var pageH = $(document).height();
	var topPx = $(this).offset().top;
	var topNum = null;
	
	if(pageH >1200) {
	    if(topPx +600>pageH ) {
	         topNum = topPx -600;
	    } else {
	        topNum = topPx; 
	     }
	} else {
	     topNum = 50;
	}
	dataObj.offset = [topNum+'px',''];
	
	

    layer.photos(dataObj)
    return false;
})

 window.onunload = function(){
	layer.closeAll();
}





